package com.github.ginirohikocha.dbm.adapter;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.ginirohikocha.dbm.Address;
import com.github.ginirohikocha.dbm.R;
import com.github.ginirohikocha.dbm.activity.MainActivity;
import com.github.ginirohikocha.dbm.activity.OrderDetailActivity;
import com.github.ginirohikocha.dbm.entity.Order;
import com.github.ginirohikocha.dbm.util.HttpUtil;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RecycleOrderAdapter extends RecyclerView.Adapter<RecycleOrderAdapter.OrderHolder> {

    private SharedPreferences workerInfo;
    //上下文
    private MainActivity activity;
    //数据列表
    private List<Order> list;

    public RecycleOrderAdapter(Context context, List<Order> list) {
        this.activity = (MainActivity)context;
        this.list = list;
        workerInfo = activity.getSharedPreferences("worker", 0);
    }

    @NonNull
    @Override
    public OrderHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_order , viewGroup , false);
        return new OrderHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull OrderHolder orderHolder, int i) {
        orderHolder.order = list.get(i);
        orderHolder.initComponent();
        orderHolder.initOper();
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    /**
     * 更新List数据
     * **/
    public void update(List<Order> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    /**
     * 订单单元Holder
     * **/
    class OrderHolder extends RecyclerView.ViewHolder {
        //布局组件
        private LinearLayout itemOrder;
        private TextView title, subtitle, content, status, price;
        private Button operationMain, operationSub;
        //订单内容
        private Order order;

        private OrderHolder(final View itemView) {
            super(itemView);
            itemOrder = itemView.findViewById(R.id.item_order_main);//订单整体
            title = itemView.findViewById(R.id.item_order_orderTitle);//订单标题
            subtitle = itemView.findViewById(R.id.item_order_orderSubtitle);//订单副标题
            content = itemView.findViewById(R.id.item_order_orderContent);//订单内容
            status = itemView.findViewById(R.id.item_order_orderStatus);//订单状态
            price = itemView.findViewById(R.id.item_order_orderEstimatedPrice);//订单价格
            operationMain = itemView.findViewById(R.id.item_order_operationMain);//订单主操作
            operationSub = itemView.findViewById(R.id.item_order_operationSub);//订单副操作
        }

        private void initComponent() {
            title.setText(order.getFaultDescription());
            content.setText(order.getContactAddress());
            status.setText(order.transferStatus());
            if (order.getEstimatedPrice() != null)
                price.setText(String.format(Locale.CHINESE, "¥%.2f", order.getEstimatedPrice()));
            else
                price.setVisibility(View.GONE);
            if (order.getOrdertime() != null)
                subtitle.setText(String.format(Locale.CHINESE, "%tF %tT", order.getOrdertime(), order.getOrdertime()));
            else
                subtitle.setText(R.string.defaultTime);
            //订单单元整体点击打开订单详情
            itemOrder.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d("订单详情", order.toString());
                    Intent intent = new Intent(activity, OrderDetailActivity.class);
                    intent.putExtra("orderNum", order.getOrderNum());
                    activity.startActivityForResult(intent, 1);
                }
            });
            //主操作点击进行操作
            operationMain.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    executeOperation();
                }
            });
            //副操作点击进行操作
            operationSub.setText(activity.getResources().getString(R.string.oper_hand_over));
            operationSub.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    activity.refresh();
                    updateOrder(2);
                }
            });
        }

        private void initOper() {
            String status = order.getStatus();
            switch (status) {
                case "待派单":
                case "待接单":
                    operationMain.setText(R.string.oper_accept);
                    break;
                case "已确认":
                    operationMain.setText(R.string.oper_finish);
                    break;
                case "已完成":
                    operationMain.setText(R.string.oper_collect);
                    break;
                default:
                    operationSub.setVisibility(View.GONE);
                case "已接单":
                    operationMain.setVisibility(View.GONE);
                    break;
            }
        }

        private void executeOperation() {
            String status = operationMain.getText().toString();
            switch (status) {
                case "接单":
                    updateOrder(0);
                    break;
                case "完成":
                    updateOrder(1);
                    break;
                case "确认收款":
                    updateOrder(3);
                    break;
            }
        }

        /**
         * @param type 0=接单;1=完成;2=移交;3=确认收款
         * **/
        private void updateOrder(int type) {
            JSONObject jsonObject = new JSONObject();
            order.setWorkerid(workerInfo.getInt("id", -1));
            if (order.getWorkerid() == -1) {
                Toast.makeText(activity, "数据错误", Toast.LENGTH_LONG).show();
                return;
            }
            jsonObject.put("order", order);

            switch (type){
                case 0:
                    jsonObject.put("newStatus", "已接单");
                    break;
                case 1:
                    jsonObject.put("newStatus", "已完成");
                    break;
                case 2:
                    jsonObject.put("newStatus", "已移交");
                    break;
                case 3:
                    jsonObject.put("newStatus", "已付款");
            }

            RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), jsonObject.toJSONString());

            HttpUtil.sendOkHttpPostRequest(Address.ORDER_UPDATE, requestBody, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(activity, "网络连接错误", Toast.LENGTH_LONG).show();
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String responseBody = response.body().string();
                    Log.d("订单更新", responseBody);
                    final JSONObject json = JSON.parseObject(responseBody);
                    if (json.getBoolean("succ")) {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(activity, "操作成功", Toast.LENGTH_LONG).show();
                                activity.refresh();
                            }
                        });
                    } else {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(activity, json.getString("msg"), Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }
            });
        }

    }
}
